package com.alogic.swagger.core;

import com.alogic.xscript.AbstractLogiclet;
import com.alogic.xscript.ExecuteWatcher;
import com.alogic.xscript.Logiclet;
import com.alogic.xscript.LogicletContext;
import com.alogic.xscript.doc.XsArray;
import com.alogic.xscript.doc.XsObject;
import com.alogic.xscript.doc.json.JsonArray;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;
import org.apache.commons.lang3.StringUtils;

import java.util.List;

/**
 * Server variable
 *
 * @since 1.6.13.7 [20200812 duanyy] <br>
 */
public class SwaggerServerVariable extends AbstractLogiclet {
    private String $name;
    private String $default;
    private String $enum;
    private String $desc;

    public SwaggerServerVariable(String tag, Logiclet p) {
        super(tag, p);
    }

    @Override
    public void configure(Properties p){
        super.configure(p);
        $enum = PropertiesConstants.getRaw(p,"enum",$enum);
        $desc = PropertiesConstants.getRaw(p,"description",$desc);
        $name = PropertiesConstants.getRaw(p,"name",$name);
        $default = PropertiesConstants.getRaw(p,"default",$default);
    }

    @Override
    protected void onExecute(XsObject root, XsObject current, LogicletContext ctx, ExecuteWatcher watcher) {
        String name = PropertiesConstants.transform(ctx,$name,"");
        if (StringUtils.isNotEmpty(name)){
            XsObject vairables = current.getObjectChild("variables",true);
            XsObject newObject = vairables.getObjectChild(name,true);
            newObject.addProperty("default",PropertiesConstants.transform(ctx,$default,""));
            newObject.addProperty("description",PropertiesConstants.transform(ctx,$desc,""));
            String [] enums = PropertiesConstants.transform(ctx,$enum,"").split(",");
            if (enums.length > 0){
                XsArray array = newObject.getArrayChild("enum",true);
                if (array instanceof JsonArray){
                    JsonArray jsonArray = (JsonArray)array;
                    List<Object> content = (List<Object>)jsonArray.getContent();
                    for (String item:enums){
                        if (StringUtils.isNotEmpty(item)){
                            content.add(item);
                        }
                    }
                }
            }
        }
    }
}